var SCRIBEFIRE_UPLOAD = {
	finalCallback : null,
	
	fileUrl : null,
	
	load : function (filePath, callback) {
		this.fileUrl = null;
		
		document.getElementById("image-button").setAttribute("busy", "true");
		
		if (filePath) {
			SCRIBEFIRE_UPLOAD.fileUrl = decodeURIComponent(filePath);
			var thefile = PerFormancingFileIO.fileFromPath(SCRIBEFIRE_UPLOAD.fileUrl);
			gTempObject = thefile;
			this.confirmUploadType();
		}
		
		this.finalCallback = callback;
		
		// Only prompt for an upload method if they're opening it from the editor.
		var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
		                        .getService(Components.interfaces.nsIPromptService);
		var check = { value : false };
		var flags = prompts.BUTTON_POS_0 * prompts.BUTTON_TITLE_IS_STRING + prompts.BUTTON_POS_1 * prompts.BUTTON_TITLE_IS_STRING + prompts.BUTTON_POS_2 * prompts.BUTTON_TITLE_CANCEL;
	
		var button = prompts.confirmEx(
				window, 
				performancingUI.getLocaleString("Upload Type"),
				"Do you want to upload an image from your computer, or insert an image already on the Web?",
				flags, 
				"Upload",
				"From Web",
				performancingUI.getLocaleString("cancel"),
				null, 
				check);
		
		if (button == 0) {
			this.selectFiles();
		}
		else if (button == 1) {
			var imageUrl = prompt("Enter the URL of the image.");
			
			if (imageUrl) {
				currentImagePath = imageUrl;
				
				this.onDialogAccept();
			}
			else {
				this.cancel();
			}
		}
		else if (button == 2){
			this.cancel();
		}
	},
	
	selectFiles : function () {
		this.filePicker(true);
	},
	
	filePicker : function (imageFilter) {
		var nsIFilePicker = Components.interfaces.nsIFilePicker;
		var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);

		if (imageFilter){
			fp.appendFilters(nsIFilePicker.filterImages);
			var localeString = performancingUI.getLocaleString('selectimagefile');
		}
		else {
			var localeString = performancingUI.getLocaleString('selectfile');
		}

		fp.init(window, localeString, nsIFilePicker.modeOpen);
		var res = fp.show();

		if (res == nsIFilePicker.returnOK){
			var thefile = fp.file;
			gTempObject = thefile;
			SCRIBEFIRE_UPLOAD.fileUrl = thefile.path;
			this.confirmUploadType();
		}
		else {
			this.cancel();
		}
	},
	
	confirmUploadType : function () {
		// Check if it should be FTP or API.
		/*
		// Only prompt for an upload method if they're opening it from the editor.
		var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
		                        .getService(Components.interfaces.nsIPromptService);
		var check = { value : false };
		var flags = prompts.BUTTON_POS_0 * prompts.BUTTON_TITLE_IS_STRING + prompts.BUTTON_POS_1 * prompts.BUTTON_TITLE_IS_STRING + prompts.BUTTON_POS_2 * prompts.BUTTON_TITLE_IS_STRING;
	
		var button = prompts.confirmEx(
				window, 
				performancingUI.getLocaleString("Upload Type"),
				performancingUI.getLocaleString("uploadMethodChoice"),
				flags, 
				performancingUI.getLocaleString("API"),
				performancingUI.getLocaleString("FTP"),
				performancingUI.getLocaleString("cancel"),
				null, 
				check);
		
		if (button == 0) {
			*/
			// API
			this.onBlogApiUploadStarted();
			/*
		}
		else if (button == 1) {
			
			// FTP
			this.onUploadStarted();
		}
		else if (button == 2) {
			// Cancel
			this.cancel();
		}*/
	},
	
	upload : function () {
		this.acceptUpload();
	},
	
	cancel : function () {
		if (gPFFChannel) {
			gPFFChannel.cancel(gPFF_MAGIC_NUMBER + 2);
		}
		
		document.getElementById("image-button").setAttribute("busy", "false");
	},
	
	///////
	
	get prefs() { return oPerformancingUtil.prefs; },
	
	acceptUpload : function () {
		var imageUrl = currentImagePath;
		
		if (!imageUrl) {
			imageUrl = SCRIBEFIRE_UPLOAD.fileUrl;
			
			if (!imageUrl) {
				re[0] = false;
				return true;
			}
			else {
				this.confirmUploadType();
			}
		}
		else {
			// @todo-ftp
			var theURL = window.arguments[1];
			var re = window.arguments[0]; 
			theURL[0] = imageUrl;
			re[0] = true;

			return true;
		}
		
		return false;
	},
	
	//CopyURl to clipboard
    copyURLToClipboard: function(aURL){
        if (currentImagePath != ""){
            try{
                var clipBoard = gPFFCC["@mozilla.org/widget/clipboardhelper;1"].getService(gPFFCI.nsIClipboardHelper);
                //clipBoard.copyString(aURL);
                clipBoard.copyString(currentImagePath);
            }catch(e){
                var localeString = performancingUI.getLocaleString('cantsaveurltoclip');
                alert(localeString);
            }
            return true;
        }
    },

    tryUpload: function() {
		var prefs = this.prefs;
		var stringBundle = document.getElementById("performancingstrings");

		var username = pffEditorUI.parentWindow.SCRIBEFIRE_BLOG.ftp_username;
		var host = pffEditorUI.parentWindow.SCRIBEFIRE_BLOG.ftp_host;
		var password = oPerformancingUtil.usermanagment.getPassword(username, "-ftp-" + host);
		var path = pffEditorUI.parentWindow.SCRIBEFIRE_BLOG.ftp_path;
		var url_to_path = pffEditorUI.parentWindow.SCRIBEFIRE_BLOG.ftp_url_to_path;
		var theProtocol = pffEditorUI.parentWindow.SCRIBEFIRE_BLOG.ftp_protocol;
		
		if (host != "" && username != "" && password != "" ){
			var theFilePath = SCRIBEFIRE_UPLOAD.fileUrl;
			
			if(theFilePath != ""){
				this.deckToggle(true);
				var theFileName = gTempObject.leafName;
				gUploadService.sendBinaryImage(theFilePath, theProtocol, username, password, host, path + theFileName);
			}
			else{
				var localeString = performancingUI.getLocaleString('selectafile');
				alert(localeString);
			}
		}
		else {
			var localeString = performancingUI.getLocaleString('setupftp');
			alert(localeString);
		}
    },
    
	tryMediaBlogUpload: function() {
		if (pffEditorUI.parentWindow.SCRIBEFIRE_BLOG.type.indexOf("blogger") != -1){
			// Special treatment for Blogger: Upload to Picasa Web Album
			
			this.deckToggle(true);
            
			try {
				var logoutReq = new XMLHttpRequest();
				logoutReq.open("GET", "https://www.google.com/accounts/Logout", false);
				logoutReq.send(null);
				
				var url = "https://www.google.com/accounts/ClientLogin";
			
				var args = {};
				args.Email = pffEditorUI.parentWindow.SCRIBEFIRE_BLOG.serviceObject.username;
				args.Passwd = pffEditorUI.parentWindow.SCRIBEFIRE_BLOG.serviceObject.password;
				args.service = 'bookmarks';

				var postData = pffCreatePostRequest(args);

				var req = new XMLHttpRequest();
				req.open("POST", url, true);
				req.setRequestHeader("Content-Type","multipart/form-data; boundary=" + postData.boundary);
				req.setRequestHeader("Content-Length", (postData.requestBody.available()));
				req.overrideMimeType("text/plain");

				req.onreadystatechange = function () {
					if (req.readyState == 4) {
						if (req.status == 200) {
							// Set a cookie.
						
							function addCookie(name, value) {
								var uri = Components.classes["@mozilla.org/network/standard-url;1"].createInstance(Components.interfaces.nsIURI);
								var cservice = Components.classes["@mozilla.org/cookieService;1"].getService().QueryInterface(Components.interfaces.nsICookieService);
								uri.spec = "http://google.com/";
								var cookieString = '';
								cookieString += name + '=' + value + ';';
								cookieString += 'domain=google.com;';
								cookieString += 'path=/;';
							
								cservice.setCookieString(uri, null, cookieString, null);
							}
						
							var cookieString = req.responseText.replace(/^\s+|\s+$/g, "").split("\n");
							for (var i = 0; i < cookieString.length; i++){
								var parts = cookieString[i].split("=");
								addCookie(parts[0], parts[1]);
							}
						
							var tokenReq = new XMLHttpRequest();
							var url ="https://www.google.com/accounts/AuthSubRequest"
								+ "?scope="+encodeURIComponent('http://picasaweb.google.com/data/')
								+ "&next="+ encodeURIComponent('http://www.scribefire.com/token.php')
								+ "&session=0";
							tokenReq.open("GET", url, true);
						     
							tokenReq.onreadystatechange = function () {
								if (tokenReq.readyState == 4) {
									if (tokenReq.status != 200) {
										alert(performancingUI.getLocaleString("upload.error.authTokenRequest") + " ("+tokenReq.status+") " + url);
										
										SCRIBEFIRE_UPLOAD.onUploadError(performancingUI.getLocaleString("upload.error.authTokenRequest"));
										return;
									}
								
									var t = tokenReq.responseText;
									
									var matches3 = t.match(/secTok['"][^>]+value=['"]([^'"]+)['"]/im);
									var matches2 = t.match(/timeStmp['"][^>]+value=['"]([^'"]+)['"]/im);
									var matches = t.match(/<form[^>]+action=['"]([^'"]+)['"]/im);
								
									try {
										var aUrl = matches[1].replace(/&amp;/g, "&");
										var time = matches2[1];
										var secTok = matches3[1];
									} catch (e) {
										SCRIBEFIRE_UPLOAD.onUploadError(performancingUI.getLocaleString("upload.error.authTokenAcquire"));
										return;
									}
									
									var allowRequest = new XMLHttpRequest();
								
									var args = {
										"timeStmp" : time,
										"secTok" : secTok,
										"at" : "",
										"allow" : "Grant access"
									};
								
									var argstring = "";
									for (var i in args) {
										argstring += i + "=" + args[i] + "&";
									}
								
									allowRequest.open("POST", aUrl, true);
									allowRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
									allowRequest.setRequestHeader("Content-Length", argstring.length);
								
									allowRequest.onreadystatechange = function () {
										if (allowRequest.readyState == 4) {
											if (allowRequest.status != 200) {
												alert(performancingUI.getLocaleString("upload.error.authTokenAcquireContact") + " ("+allowRequest.status+") " + aUrl);
												
												SCRIBEFIRE_UPLOAD.onUploadError(performancingUI.getLocaleString("upload.error.authTokenAcquireContact"));
												return;
											}
											
											var token = allowRequest.responseText;
										
											var aNsiFile = gTempObject;
											var mimeSvc = Components.classes["@mozilla.org/mime;1"].getService(Components.interfaces.nsIMIMEService);
								            var theMimeType = mimeSvc.getTypeFromFile(aNsiFile);
										
											const MULTI = "@mozilla.org/io/multiplex-input-stream;1";
											const FINPUT = "@mozilla.org/network/file-input-stream;1";
											const BUFFERED = "@mozilla.org/network/buffered-input-stream;1";

											const nsIMultiplexInputStream = Components.interfaces.nsIMultiplexInputStream;
											const nsIFileInputStream = Components.interfaces.nsIFileInputStream;
											const nsIBufferedInputStream = Components.interfaces.nsIBufferedInputStream;

											var buf = null;
											var fin = null;

											var fpLocal  = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
											fpLocal.initWithFile(aNsiFile);

											fin = Components.classes[FINPUT].createInstance(nsIFileInputStream);				
											fin.init(fpLocal, 1, 0, false); 

											buf = Components.classes[BUFFERED].createInstance(nsIBufferedInputStream);
											buf.init(fin, 9000000);
										
											var uploadStream = Components.classes[MULTI].createInstance(nsIMultiplexInputStream);
											uploadStream.appendStream(buf);
										
											var upreq = new XMLHttpRequest();
											upreq.open("POST", "http://picasaweb.google.com/data/feed/api/user/default/albumid/default", true);
											upreq.setRequestHeader("Authorization","AuthSub token="+token);
											upreq.setRequestHeader("Content-Type", theMimeType);
											upreq.setRequestHeader("Content-Length", (uploadStream.available()));
											upreq.overrideMimeType("text/xml");
										
											upreq.onreadystatechange = function () {
												if (upreq.readyState == 4) {
													if (upreq.status < 300) {
														try {
															var imageUrl = upreq.responseXML.getElementsByTagName("content")[0].getAttribute("src") + "?imgmax=800";
															SCRIBEFIRE_UPLOAD.uploadBlogAPIGood(imageUrl);
														} catch (e) {
															SCRIBEFIRE_UPLOAD.onUploadError(performancingUI.getLocaleString("upload.error.googleError", [upreq.responseText]));
														}
													}
													else {
														if (upreq.responseText.match(/Must sign terms/i)) {
															performancingUI.openInTab("http://picasaweb.google.com/");
															alert(performancingUI.getLocaleString("upload.error.picasaTerms"));
														}
														else {
															SCRIBEFIRE_UPLOAD.onUploadError(performancingUI.getLocaleString("upload.error.noApi"));
														}
													}
												}
											};
										
											upreq.send(uploadStream);
										}
									};
								
									allowRequest.send(argstring);
								}
							};
						
							tokenReq.send(null);
						}
						else {
							SCRIBEFIRE_UPLOAD.onUploadError(performancingUI.getLocaleString("upload.error.noLogin"));
						}
					}
				};

				req.send(postData.requestBody);	
			} catch (e) {
				this.onUploadError(performancingUI.getLocaleString("theerror", [e]));
				return;
			}
		}
		else {
            var theFilePath = SCRIBEFIRE_UPLOAD.fileUrl;

			this.deckToggle(true);
			gUploadService.doMediaFileUpload(gTempObject);
		}
    },
    
    //On Upload Start
    onUploadStarted: function() {
        var localeString = performancingUI.getLocaleString('uploading');
        gUploadService.serviceType = "ftp";
        this.tryUpload();
    },
    
    //Start Blog API upload (newMediaObject)
    onBlogApiUploadStarted: function() {
	    var localeString = performancingUI.getLocaleString('uploading');
        this.tryMediaBlogUpload();
        gUploadService.serviceType = "blogapi";
    },
    
    uploadFTPGood: function() {
        var localeString = performancingUI.getLocaleString('uploadcanceled');
        this.setFeedbackText(localeString, false);
        this.deckToggle();
        this.onFtpUploadDone();

		if (this.onDialogAccept()) {
			if (!document.getElementById("ftp-upload-window")) {
				window.close();
			}
		}
    },
    
    uploadBlogAPIGood: function(aURL) {
        var localeString = performancingUI.getLocaleString('uploadcanceled');
        this.setFeedbackText(localeString, false);
        this.deckToggle();
        this.onBlogAPIUploadDone(aURL);

		if (this.onDialogAccept()) {
			if (!document.getElementById("ftp-upload-window")) {
				window.close();
			}
		}
    },
    
    //Set upload status here:
    setFeedbackText: function(aText, isError) {
		if (isError) {
			alert(aText);
		}
    },
    
    //On FTP Upload success
    onFtpUploadDone: function() {
	    var url_to_path = pffEditorUI.parentWindow.SCRIBEFIRE_BLOG.ftp_url_to_path;
        currentImagePath = url_to_path + gTempObject.leafName;
		try { document.getElementById("uploaded-file-url").value = url_to_path + gTempObject.leafName; } catch (e) { };
		
    },
    
    onBlogAPIUploadDone: function(aURL) {
	    currentImagePath = aURL;
		try { document.getElementById("uploaded-file-url").value = aURL; } catch (e) { };
    },
    
    onDialogAccept: function() {
		if (this.finalCallback) {
			this.finalCallback(currentImagePath);
		}
		
		document.getElementById("image-button").setAttribute("busy", "false");
    },
    
    setErrorTimer: function(){
        gTheErrorTimer = window.setTimeout(function () { SCRIBEFIRE_UPLOAD.deckToggle(); }, 1000);
    },
    
    cancelErrorTimer: function(){
        window.clearTimeout(gTheErrorTimer);
    },
    
    onUploadError: function(theError){
        var localeString2 = performancingUI.getLocaleString('theerror', [theError]);
        this.setFeedbackText(localeString2, true);
    },
    
    deckToggle : function (notError) {
    },

	///

	onDataAvailable: function(aChannel, aCtxt, aInStr, aSourceOffset, aCount) {},
	onStartRequest: function(aChannel, aCtxt) {},
	onStopRequest: function(aChannel, aCtxt, aErrCode) {
	  gUploadService.onReturn(aErrCode);
	}
	
};

var gPffTempUploadObject = [];
var currentImagePath = "";

var oPerformancingUtil = pffEditorUI.parentWindow.gPerformancingUtil;

var gPFF_MAGIC_NUMBER = 0x804b0000;
var gPFFNetErrorStrings = {
   "1": "Unexpected Error",                    //unexpected
   "2": "User Canceled Upload",                //usercancel
  "13": "FTP Refused Upload",                  //refused
  "14": "Network Timeout",                     //netTimeout
  "16": "Network Appears Offline",             //netOffline
  "21": "Incorrect User or Password",          //ftplogin
  "22": "ftpcwd",                              //ftpcwd
  "23": "ftppasv",                             //ftppasv
  "24": "Incorrect Password",                  //ftppwd
  "25": "ftplist",                             //ftplist
  "30": "Unknown Error"                        //unknown
};
var gPFFCI = Components.interfaces;
var gPFFCC = Components.classes;
var gPFFChannel = null;
var gTheErrorTimer = null;

var gTempObject = [];

var gUploadService = new Object();

gUploadService = {
    serviceType: null,
    //this.CR = Components.results;
    
	get prefs() { return oPerformancingUtil.prefs; },

    // uploads stream (nsIInputStream) to the specified location (nsIURI)
    upload: function(stream, uri) {
      var iosvc = gPFFCC["@mozilla.org/network/io-service;1"].getService(gPFFCI.nsIIOService);
      gPFFChannel = iosvc.newChannelFromURI(uri).QueryInterface(gPFFCI.nsIUploadChannel);
      gPFFChannel.setUploadStream(stream, "", -1);
      gPFFChannel.asyncOpen(SCRIBEFIRE_UPLOAD, window);
    },
    
    // returns an nsIInputStream suitable for passing to nsIUploadChannel.setUploadStream
    // aFile is the nsILocalFile, whose contents should be uploaded
    getUploadStreamForFile: function(aFile) {
      var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
      fstream.init(aFile, 1, 0, 0);
    
      var bufStream = gPFFCC["@mozilla.org/network/buffered-input-stream;1"].createInstance(gPFFCI.nsIBufferedInputStream);
      bufStream.init(fstream, 8192);
      return bufStream;
    },
    
    getTargetURI: function(aProtocol, aUserName, aPassword, aHost, aPath) {
      var uri = gPFFCC["@mozilla.org/network/standard-url;1"].createInstance(gPFFCI.nsIURI);
      //uri.spec = "ftp://"+aUserName+":"+aPassword+"@"+ftpURi;
      uri.spec = aProtocol + "://" + aUserName + ":" + aPassword + "@" + aHost + "/" + aPath;
      return uri;
    },
    
    sendBinaryImage: function(theFilePath, aProtocol, aUserName, aPassword, aHost, aPath) {
        var myFile = gTempObject; //Use the picked file, not the path from the textbox.
        this.upload(this.getUploadStreamForFile(myFile), this.getTargetURI(aProtocol, aUserName, aPassword, aHost, aPath));
    },
    
    getErrorStr: function(aCode){
      if(aCode == 0) return "done";
      if(aCode < gPFF_MAGIC_NUMBER) return "notneterror";
      aCode %= gPFF_MAGIC_NUMBER;
      //LOG(this.aCode);
      if(aCode in gPFFNetErrorStrings){
        return gPFFNetErrorStrings[aCode];
      }
      return "unexpected";
    },
    
	cancelUpload: function() {
		if (gPFFChannel) {
			gPFFChannel.cancel(gPFF_MAGIC_NUMBER + 2);
		}
	},
    
    onReturn: function(aCode) {
        if (aCode == 0) {
			// success
            SCRIBEFIRE_UPLOAD.uploadFTPGood();
        }
		else {
			// xxx beep, perhaps?  // failure - don't close
            var theError = this.getErrorStr(aCode);
            SCRIBEFIRE_UPLOAD.onUploadError(theError, aCode);
        }
    },
    
    //Prep Binary Data
    prepBinaryToBase64Data: function(aNsiFile) {
		return btoa(this.getBinaryData(aNsiFile));
    },
    
	getBinaryData : function (aNsiFile) {
        var fileInStream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream); 
        fileInStream.init(aNsiFile, 0x01, 0644, false);
        var binaryInStream = Components.classes["@mozilla.org/binaryinputstream;1"] .createInstance(Components.interfaces.nsIBinaryInputStream); 
        binaryInStream.setInputStream(fileInStream); 
        var theData = binaryInStream.readBytes( binaryInStream.available() );
		return theData;
	},

    //Do newMediaObject File Upload
    //metaWeblog.newMediaObject (blogid, username, password, struct)
    doMediaFileUpload: function(aNsiFile) {
		var theBase64Data = this.prepBinaryToBase64Data(aNsiFile);

		var mimeSvc = Components.classes["@mozilla.org/mime;1"].getService(Components.interfaces.nsIMIMEService);
		var theMimeType = mimeSvc.getTypeFromFile(aNsiFile);
		
		if (pffEditorUI.parentWindow.SCRIBEFIRE_BLOG.serviceObject.fileUpload) {
			var myResponse = pffEditorUI.parentWindow.SCRIBEFIRE_BLOG.serviceObject.fileUpload(aNsiFile.leafName, theMimeType, theBase64Data);
			
			//Do and handle the Post Request
			var theCall = new PffXmlHttpReq(pffEditorUI.parentWindow.SCRIBEFIRE_BLOG.api, "POST", myResponse, false, null, null, null);
			theCall.onResult  = function(aText, aXML){
				gUploadService.onBlogApiResponse( aText, aXML, pffEditorUI.parentWindow.SCRIBEFIRE_BLOG.url );
			}
			theCall.onError  = function(aText, aXML){
				var localeString = performancingUI.getLocaleString('errorcontactingserver');
				SCRIBEFIRE_UPLOAD.onUploadError(localeString,"");
			}
			theCall.prepCall(); //Set up The call (open connection, etc.)
			theCall.request.setRequestHeader("Content-Type", "text/xml");
			theCall.makeCall(); //Make the call
			theCall.request.overrideMimeType ('text/xml');
		}
		else {
			SCRIBEFIRE_UPLOAD.setFeedbackText("Your blog does not support image uploads, or if it does, it is not configured correctly.", true);
			SCRIBEFIRE_UPLOAD.cancel();
		}
    },
    
    onBlogApiResponse: function(aResponseText, aResponseXML, aBlogUrl) {
        var re = /(\<\?\xml[0-9A-Za-z\D]*\?\>)/;
        var newstr = aResponseText.replace(re, "");

		try {
			var e4xXMLObject = new XML(newstr);
		} catch (e) {
			SCRIBEFIRE_UPLOAD.setFeedbackText("Your blog does not support image uploads, or if it does, it is not configured correctly.", true);
			SCRIBEFIRE_UPLOAD.cancel();
			return;
		}
		
        gPffTempUploadObject.push(e4xXMLObject);
		
        var ourParsedResponse = null; 
        if (e4xXMLObject.params.param.value.length() >= 1){
            ourParsedResponse = bfXMLRPC.XMLToObject(e4xXMLObject.params.param.value.children()[0]); 
        }else if (e4xXMLObject.fault.value.length() >= 1){
            ourParsedResponse = bfXMLRPC.XMLToObject(e4xXMLObject.fault.value.children()[0]); 
        }
        gPffTempUploadObject.push(ourParsedResponse);
        if(ourParsedResponse.faultString || !ourParsedResponse.url){
            var localeString = "";
            var localeString2 = performancingUI.getLocaleString('noImageUpload');
            var localeString3 = performancingUI.getLocaleString('noImageUpload2');
            if(ourParsedResponse.faultString){
                localeString = performancingUI.getLocaleString('requesterror', [ ourParsedResponse.faultString ]);
            }

            alert(localeString2 + "\n\n" + localeString3 + "\n\n" + localeString);

            SCRIBEFIRE_UPLOAD.onUploadError(ourParsedResponse.faultString,"");
        }else if(ourParsedResponse.url){
            //Construct the URL
            var theNewURL = "";
            if( /https?:/.test(ourParsedResponse.url.toString()) ){
                theNewURL = ourParsedResponse.url;
            }else{
                if(aBlogUrl.charAt(aBlogUrl.length -1) == "/" && ourParsedResponse.url.charAt(0) == "/"){
                    theNewURL = aBlogUrl.substr(0, aBlogUrl.length -1) + ourParsedResponse.url;
                }else{
                    theNewURL = aBlogUrl + ourParsedResponse.url;
                }
            }
            SCRIBEFIRE_UPLOAD.uploadBlogAPIGood(theNewURL);
        }
    }
}

function pffCreatePostRequest(args) {
	const BOUNDARY="---------------------------32191240128944"; 
	
	const MULTI = "@mozilla.org/io/multiplex-input-stream;1";
	const STRINGIS = "@mozilla.org/io/string-input-stream;1";
	const BUFFERED = "@mozilla.org/network/buffered-input-stream;1";
													   
	const nsIMultiplexInputStream = Components.interfaces.nsIMultiplexInputStream;
	const nsIStringInputStream = Components.interfaces.nsIStringInputStream;
	const nsIBufferedInputStream = Components.interfaces.nsIBufferedInputStream;
	
	var sheader = '';
	
	for (var i in args) {
		sheader += "--" + BOUNDARY + "\r\n";
		sheader += "Content-Disposition: form-data; name=\"" + encodeURIComponent(i) + "\"";
		
		if (typeof args[i] == "object") {
			if (args[i].type == 'file') {
				sheader += " filename=\"" + args[i].filename + "\"";
			
				if (args[i].headers.length > 0) {
					for (var q = 0; q < args[i].headers.length; q++){
						sheader += "\r\n" + args[i].headers[q];
					}
				}
			
				sheader += args[i].content;
			}
		}
		
		sheader += "\r\n";
		
		sheader += "\r\n";
		sheader += args[i];
		sheader += "\r\n";
	}
	
	sheader += "--" + BOUNDARY + "--\r\n";
	sheader = encodeToUtf8(sheader);
	var hsis = Components.classes[STRINGIS].createInstance(nsIStringInputStream);
	hsis.setData(sheader,sheader.length);

	var uploadStream = Components.classes[MULTI].createInstance(nsIMultiplexInputStream);
	uploadStream.appendStream(hsis);
	
	return { "requestBody" : uploadStream, "boundary": BOUNDARY };
	
	function encodeToUtf8(oStr) {
		var utfStr = oStr;
		var uConv = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter); 
		uConv.charset = "UTF-8";	 	 
		utfStr = uConv.ConvertFromUnicode (oStr);	 	 
		return utfStr;
	}
}